package org.leetcode.middle.leetcode1143;

import java.util.Arrays;

public class Solution {


    public int longestCommonSubsequence3(String text1, String text2) {

        int n1 = text1.length();
        int n2 = text2.length();

        int[][] dp = new int[n1 + 1][n2 + 1];

        int maxLength = 0;

        for (int i = 1; i <= n1; i++) {
            for (int j = 1; j <= n2; j++) {
                if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    //dp[i - 1][j]表示跳过当前text1指向的字符
                    //dp[i][j - 1]表示跳过当前text2指向的字符
                    //不直接考虑dp[i-1][j-1]是因为：全部忽略text1指向的字符和text2指向的字符会遗漏一些数据
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }

                maxLength = Math.max(maxLength, dp[i][j]);
            }
        }

        return maxLength;
    }

    public int longestCommonSubsequence2(String text1, String text2) {

        int[][] dp = new int[text1.length() + 1][text2.length() + 1];

        for (int i = 1; i <= text1.length(); i++) {
            for (int j = 1; j <= text2.length(); j++) {
                if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[text1.length()][text2.length()];
    }


    public int longestCommonSubsequence(String text1, String text2) {

        //dp[i][j] 表示 text1 的前 i 个字符和 text2 的前 j 个字符的最长公共子序列的长度。
        //dp[0][0]为0
        int[][] dp = new int[text1.length() + 1][text2.length() + 1];

//        for (int [] dp1:dp) {
//            Arrays.fill(dp1,0);
//        }

        for (int i = 1; i <= text1.length(); i++) {
            for (int j = 1; j <= text2.length(); j++) {
                if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }

            }
        }

        return dp[text1.length()][text2.length()];
    }


    public static void main(String[] args) {
        Solution solution = new Solution();

        int i = solution.longestCommonSubsequence("abcde", "ace");
        System.out.println(i);
    }
}
